package cn.edu.neu.softlab633.influencemaximization.sy.input;

import cn.edu.neu.softlab633.influencemaximization.sy.bean.Graph;
import cn.edu.neu.softlab633.influencemaximization.sy.bean.Index;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Jason on 2017/5/10.
 */
public class GraphReader {
    public static Graph readGraphFromCSV(String g1_filepath, String g2_filepath, String alignment_filepath) throws IOException {
        Index outgoingIndex = new Index();
        Index ingoingIndex = new Index();
        getIndex(g1_filepath, outgoingIndex, ingoingIndex, 1, 1);
        getIndex(g2_filepath, outgoingIndex, ingoingIndex, 2, 2);
        getIndex(alignment_filepath, outgoingIndex, ingoingIndex, 1, 2);
        getIndex(alignment_filepath, ingoingIndex, outgoingIndex, 1, 2);
        return new Graph(outgoingIndex, ingoingIndex);
    }

    private static void getIndex(String filepath, Index outgoingIndex, Index ingoingIndex, int arg1, int arg2) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(filepath));
        String line = br.readLine();
        while (line != null) {
            String[] tmp = line.split(",");
            int in = Integer.valueOf(tmp[0]) * 10 + arg1;
            int out = Integer.valueOf(tmp[1]) * 10 + arg2;
            String[] weight_tmp = tmp[2].split(" ");
            Double[] weight = new Double[weight_tmp.length];
            for (int i = 0; i < weight.length; i++) {
                weight[i] = Double.valueOf(weight_tmp[i]);
            }
            if (outgoingIndex.getIndex().containsKey(in)) {
                outgoingIndex.getIndex().get(in).put(out, weight);
            } else {
                Map<Integer, Double[]> edge = new HashMap<>();
                edge.put(out, weight);
                outgoingIndex.getIndex().put(in, edge);
            }
            if (ingoingIndex.getIndex().containsKey(out)) {
                ingoingIndex.getIndex().get(out).put(in, weight);
            } else {
                Map<Integer, Double[]> edge = new HashMap<>();
                edge.put(in, weight);
                ingoingIndex.getIndex().put(out, edge);
            }
            line = br.readLine();
        }
        br.close();
    }

    public static Graph graphReaderTest() throws IOException {
        String filepath = "testdata/f.txt";
        Index ingoingIndex = new Index();
        Index outgoingIndex = new Index();
        getIndex(filepath, outgoingIndex, ingoingIndex, 1, 1);
        Graph graph = new Graph(outgoingIndex, ingoingIndex);
        return graph;
    }
}
